<template>
  <div class="residentlist">
    <div class="residentlist-item"
         :class="{'residentlist-item-active': item.isChecked }"
         v-for="item in residentList"
         :key="item.id"
         @click="itemAction(item)"
    >{{item.name}}</div>
  </div>
</template>

<script>
export default {
  name: "residentCheckbox",
  data() {
    return {
      residentList: [],
      checkedList: []
    }
  },
  props: {
    // 数据源
    list: {
      type: Array,
      default: () => {
        return []
      },
    },
    // 已选择对象 逗号拼接的字符串
    checkedIds: {
      type: String,
      default: () => {
        return ''
      },
    }
  },
  mounted() {
    this.checkedList = []
    this.list.forEach(item => {
      this.$set(item, 'isChecked', false)
    })
    this.residentList = this.$common.xeUtils.clone(this.list, true)
    // 回显
    const checkedIds = this.checkedIds.split(',')
    this.residentList.forEach(i => {
      checkedIds.forEach(j => {
        if (i.id == j) {
          i.isChecked = true
          this.checkedList.push(j)
        }
      })
    })

  },
  methods: {
    itemAction(item) {
      let isHas = this.checkedList.find(e => e === item.id)
      if (!isHas) {
        this.checkedList.push(item.id)
        item.isChecked = true
      } else {
        this.$common.xeUtils.remove(this.checkedList, e => e === item.id)
        item.isChecked = false
      }
      // 选中项数组
      let checkedArr = []
      this.residentList.forEach(item => {
        if (item.isChecked) checkedArr.push({ id: item.id, name: item.name})
      })
      this.$emit('change', checkedArr)
    },
  }
}
</script>

<style lang="less" scoped>
.residentlist {
  display: flex;
  justify-content: flex-start;
  flex-flow: wrap;
  align-items: center;
  margin: 0px 15px 10px;
  padding-top: 5px;

  &-item {
    box-sizing: border-box;
    padding: 5px;
    min-width: 80px;
    text-align: center;
    border: 1px solid #898989;
    border-radius: 10px;
    margin-right: 10px;
    margin-bottom: 10px;
    cursor: pointer;

    &-active {
      box-shadow: 0px 0px 5px 3px rgba(255, 145, 0, 0.8);
      border: 1px solid #FF9100;
    }
  }

}
</style>
